package com.qf.ssm.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.ssm.cache.MenuCache;
import com.qf.ssm.dto.ResultCode;
import com.qf.ssm.event.MenuCacheEvent;
import com.qf.ssm.exceptions.AddErrorException;
import com.qf.ssm.exceptions.DeleteErrorException;
import com.qf.ssm.exceptions.UpdateErrorException;
import com.qf.ssm.mapper.MenuMapper;
import com.qf.ssm.pojo.CheckStatus;
import com.qf.ssm.pojo.Menu;
import com.qf.ssm.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Service
public class MenuServiceImpl implements MenuService {

    private MenuMapper menuMapper;
    private MenuCache menuCache;
   @Autowired
    public MenuCache getMenuCache() {
        return menuCache;
    }

    private ApplicationContext context;

    @Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }

    @Autowired
    public void setMenuMapper(MenuMapper menuMapper) {
        this.menuMapper = menuMapper;
    }

    @Override
    public void addMenu(Menu menu) {

        //先对数据进行判断
        boolean isNull = menu.isNull(CheckStatus.ADD);
        if(isNull){

            //数据不符合我们的要求,还有必要继续执行吗?返回结果给前端
            throw new AddErrorException("数据不完整,请检查数据", ResultCode.DATA_NOT_ALLOW_NUL);
        }
        //然后对密码进行散列
        //将数据保存到数据库中
        menuMapper.addMenu(menu);
        context.publishEvent(new MenuCacheEvent());//更新缓存
    }

    @Override
    public void updateMenu(Menu menu) {
        if(menu.isNull(CheckStatus.UPDATE)){
            throw new UpdateErrorException("更新的数据为空", ResultCode.DATA_NOT_ALLOW_NUL);
        }
         menuMapper.updateMenu(menu);
        context.publishEvent(new MenuCacheEvent());
    }

    @Override
    public void deleteMenuByIds(Long[] ids) {
        if(ids==null || ids.length==0){
            //删除时必须又id
            throw  new DeleteErrorException("删除必须传递 id", ResultCode.DATA_NOT_ALLOW_NUL);
        }
        menuMapper.deleteMenuByIds(Arrays.asList(ids));
        context.publishEvent(new MenuCacheEvent());
    }

    @Override
    public PageInfo<Menu> getAllMenu(int page, int limit) {
        PageHelper.startPage(page,limit);
        List<Menu> userList = menuMapper.getAllMenu();
        PageInfo<Menu>pageInfo=new PageInfo<>(userList);
        return pageInfo;
    }



}
